package com.cnzxo.esp32cam;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    private static String TAG = "LYJ";

    private Handler handler = new Handler(Looper.getMainLooper());

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        System.out.println("==> ok");
        Log.d(TAG, "点击事件");
        setContentView(R.layout.activity_main);
        Button btn = findViewById(R.id.button);
        btn.setOnClickListener(view -> {
            Toast.makeText(MainActivity.this, "OK", Toast.LENGTH_SHORT).show();
            getVideoStream();
        });
    }

    private void getVideoStream() {
        OkHttpClient http = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://192.168.1.27:81/stream")
                .addHeader("Connection", "Keep-Alive")
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0")
                .build();
        http.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.d(TAG, "请求失败, error: " + e);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful() && response.body() != null) {
                    Log.d(TAG, "请求成功");
                    InputStream inputStream = response.body().byteStream();
                    byte[] bytes = new byte[2048];
                    String startKey = "Content-Type: image/jpeg\r\nContent-Length:";
                    String endKey = "\r\n--123456789000000000000987654321\r\n";
                    String bodyKey = "\r\n\r\n";
                    int length;
                    StringBuilder stream = new StringBuilder();
                    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
                    while ((length = inputStream.read(bytes)) > 0) {
                        stream.append(new String(bytes, 0, length));
                        buffer.write(bytes, 0, length);
                        int startPos = stream.indexOf(startKey);
                        if (startPos < 0) {
                            continue;
                        }
                        int endPos = stream.indexOf(endKey, startPos);
                        if (endPos < 0) {
                            continue;
                        }
                        int bodyPos = stream.indexOf(bodyKey, startPos);
                        if (bodyPos < 0) {
                            continue;
                        }
                        byte[] array = buffer.toByteArray();
                        byte[] frame = Arrays.copyOfRange(array, bodyPos + bodyKey.length(), endPos);
                        Bitmap bitmap = BitmapFactory.decodeByteArray(frame, 0, frame.length);
                        runOnUiThread(() -> {
                            ImageView imageView = (ImageView) findViewById(R.id.imageView);
                            imageView.setImageBitmap(bitmap);
                            Log.d(TAG, "Update");
                        });
                    }
                    Log.d(TAG, "请求结束");
                } else {
                    Log.d(TAG, "请求失败, code: " + response.code());
                }
            }
        });
    }
}